<template>
  <article class="page">
    <headerbar>学习资料</headerbar>
    <section class="frame-content-sub no-bg">

      <section class="inner-content pdv-9 pdh-4">

        <div class="input-row-wrap">
          <div class="name">标题：</div>
          <input v-model="form.title" type="text" placeholder="请填写标题">
        </div>


        <p class="pdv-2"></p>
        <div class="input-column-wrap">
          <div class="value-wrap">
            <cube-radio-group :horizontal="true" :options="options" v-model="form.subType" />
          </div>
        </div>

        <section v-show="form.subType === 1">
          <div class="input-row-wrap">
            <div class="name">内容：</div>
            <textarea v-model="form.spaceExt" placeholder="请填写内容" name="" id="" cols="30" rows="10"></textarea>
          </div>

          <div class="input-row-wrap">
            <div class="mgt-5 color-tip mgb-1"><i class="required color-red">严禁上传或录入涉密内容</i></div>
            <div class="name">附件：</div>
            <section class="upload-wrap">
              <cube-upload ref="upload"
                          action=""
                          accept="*/*"
                          @file-removed="removeFile"
                          :simultaneous-uploads="1"
                          @files-added="uploadFile"
                          @input="onInput"
              />
            </section>
          </div>
        </section>


        <section v-show="form.subType === 3">
          <div class="input-row-wrap">
            <div class="name">内容：</div>
            <textarea v-model="form.spaceExt" placeholder="请填写内容" name="" id="" cols="30" rows="10"></textarea>
          </div>

          <div class="input-row-wrap">
            <div class="name">选择收藏：</div>
            <!-- <div v-preventReClick="1000">点击选择</div> -->
            <cube-button class="choose_but" @click="goChoose" v-preventReClick="1000">点击选择</cube-button>
            <span class="choose_text">共选择<span>{{selectCollectList.length || 0}}</span>个收藏</span>
          </div>
        </section>

        <section v-if="form.subType === 2">
          <div class="input-row-wrap">
            <div class="name">链接：</div>
            <textarea v-model="form.externalUrl" placeholder="请填写链接"  rows="5"></textarea>
          </div>
        </section>

        <div class="pdv-6"></div>

        <div @click="save($event)" v-preventReClick="1000" class="default-block-btn">提交</div>

        <div class="pdv-5"></div>
      </section>

    </section>
  </article>
</template>

<script>
  import fileIcon from '../../../../static/images/up_document.png'

  export default {
    name: 'learningMaterialsesAdd',
    data () {
      return {
        options: [
          {
            label: '本地资料',
            value: 1
          },
          {
            label: '我的收藏',
            value: 3
          },
          {
            label: '分享链接',
            value: 2
          },
        ],
        spaceId: '',
        form: {
          subType: 1,  // 1：本地资料，2：外部链接，3：我的收藏，4：APP分享链接
          title: '',
          spaceExt: '',
          annexInfo: '',
          externalUrl: '',
          spaceType: '5'
        },
        selectCollectList: [], //从我的收藏选择的列表
        wellDeleteList: [], // 将要真实删除的文件
        forceList: [], // 之前的文件
        attachmentList: [],
        recordSubType: 1 //记录上一次选择的类型
      }
    },
    mounted () {
      let id = this.$route.query.id
      this.spaceId = id
      if (id) {
        this.form.title = this.$store.state.branchDetail.title
        this.form.spaceExt = this.$store.state.branchDetail.ext
        this.form.externalUrl = this.$store.state.branchDetail.externalUrl
        this.attachmentList = this.$store.state.branchDetail.annexList
        this.form.spaceId = id
        if (this.form.externalUrl) {
          this.form.subType = 1
        }
        this.$store.state.branchDetail.annexList.forEach(v => {
          let data = v
          data.url = this.tools.getImgUrl(v.fileId)
          this.forceList.push(v.fileId)
          this.$refs.upload.files.push(data)
        })
      }
    },
    computed: {
      subType () {
        console.log('this.form.subType1={}', this.form.subType)
        return this.form.subType
      }
    },
    watch: {
      subType: function (val) {
        console.log('this.form.subType2={}', this.form.subType)
        if (this.form.subType != this.recordSubType) {
          this.giveUpDataDialog()
        }
      }
    },
    activated () {
      console.log(this.$route.name, "activated");
      console.log('this.$store.state.selectCollectList',this.$store.state.selectCollectList)
      this.selectCollectList = this.$store.state.selectCollectList || this.selectCollectList;
    },
    beforeRouteLeave(to, from, next) {
      this.$route.meta.keepAlive = to.name === 'collectionSelection'
      if(this.$route.meta.keepAlive) {
        this.$store.commit('addRoute','learningMaterialsesAdd')
      }else {
        this.$store.commit('removeRoute','learningMaterialsesAdd')
        this.$destroy()
      }
      next()
    },
    beforeRouteEnter(to, from, next) {
      next((vm) => {
        if (to.name === "learningMaterialsesAdd") {
          to.meta.keepAlive = true;
          vm.$store.commit("addRoute", "learningMaterialsesAdd");
        }
      });
    },
    methods: {
      // 选择我的收藏
      goChoose(){
        // fromOrg表示从组织生活进入
        this.$router.push({path: '/collectionSelection'})
        // , query: {orgLifeId: ""}
      },
      removeFile (file) {
        console.log('removeFile', file)
        console.log('removeFile', this.attachmentList)
        this.attachmentList.splice(this.attachmentList.findIndex(item => {
          this.wellDeleteList.push(file.id)
          return item.fileId === file.fileId
        }), 1)
        console.log('removeFile', this.attachmentList)
      },
      /*真实删除材料，因此只能在保存时候操作*/
      delSpaceInfoAnnex (ID) {
        let params = {
          'loginId': this.tools.getUserInfo().id,
          'spaceId': this.spaceId,
          'annexId': ID,
        }
        this.fetchService.delSpaceInfoAnnex(params)
      },
      /*每次图片添加、更新都是插入动作*/
      uploadFile (file) {
        let me = this
        console.log('uploadfile', file)
        return new Promise((resolve, reject) => {
          if (file.length < 1) {
            return resolve(true)
          }
          Array.prototype.slice.call(file).forEach((v,index) => {
            console.log(index, file.length, me.attachmentList.length)
            if (!v.file) {
              if (me.attachmentList.length === file.length && index === file.length-1) {
                resolve(true)
              }
              return
            }
            (function (v) {
              let formData = new FormData()
              formData.append('file', v)
              me.fetchService.o_upload(formData).then((res) => {
                if (res.code !== 0) {
                  return me.tools.tip(res.message)
                }
                let ret = res.data
                let data = {
                  fileid: ret.fileId,
                  filename: v.name,
                  fileUrl: ret.desc
                }
                me.attachmentList.push(data)
                if (me.attachmentList.length === file.length) {
                  resolve(true)
                }
              })
            })(v.file)
          })
        })

      },
      // uploadFile (file) {
      //   let formData = new FormData()
      //   formData.append('file', file[0])
      //   this.fetchService.o_upload(formData).then((res) => {
      //     if (res.code !== 0) {
      //       return this.tools.tip(res.message)
      //     }
      //     this.attachmentList.push({
      //       'fileid': res.data.fileId,
      //       'filename': res.data.fileName,
      //       'totalBytes': res.data.totalBytes,
      //       'type': '1'
      //     })
      //   })
      // },
      getFileJson (list) {
        let ret = []
        list.forEach(v => {
          let item = {
            fileid: v.fileId || v.fileid,
            filename: v.fileName || v.filename,
            fileUrl:v.fileUrl
          }
          ret.push(item)
        })
        /**
         * 目前接口的编辑功能对文件的逻辑是：每次提交的文件都会新增，也就是说之前的文件在这次提交中再次提交的话，那么查询的时候就会出现重复，所以现在在提交前把之前的文件剔除
         */
        let noForceRet = []
        ret.forEach(item => {
          if (!this.forceList.includes(item.fileid)) {
            noForceRet.push(item)
          }
        })
        return noForceRet
      },
      save (e) {
        if (e.target.disabled) {
          return false
        }
        if (this.form.title === '') {
          return this.tools.tip('请填写标题')
        }
        if (this.form.subType != 2 && this.form.spaceExt === '') {
          return this.tools.tip('请填写内容')

        } else if (this.form.subType === 2 && this.form.externalUrl === '') {
          return this.tools.tip('请填写链接')
        }
        this.tools.showLoading('提交中...')
        this.wellDeleteList.forEach(v => {
          this.delSpaceInfoAnnex(v)
        })
        this.uploadFile(this.$refs.upload.files).then(res => {
          if (this.form.subType == 3) { //我的收藏，将选择的收藏列表赋值给annexInfo
            var arr = [];
            this.selectCollectList.forEach(v => {
              let item = {
                fileid: '/redCloudNewsDetail/' + v.contentId+'?newsType='+v.newsType,//传新闻id
                filename: v.title
              }
              arr.push(item)
              this.form.annexInfo = JSON.stringify(arr)
            })
          } else {
            let filesJson = this.getFileJson(this.attachmentList)
            this.form.annexInfo = JSON.stringify(filesJson)
          }
          console.log('---------------this.form.annexInfo=', this.form.annexInfo)
          this.fetchService.saveSpaceInfo(this.form).then(res => {
            this.tools.hideLoading()
            if (res.code !== 0) {
              return this.tools.tip(res.message)
            }
            this.tools.tip('提交成功')
            this.tools.back()
          })
        })
      },
      onInput (file) {
        this.$refs.upload.files.map((v) => {
          if (!this.tools.isImage(v.name)) {
            v.url = fileIcon
          }
          return v
        })
      },
      giveUpDataDialog () {
        let _this = this
        this.dialog = this.$createDialog({
          type: 'confirm',
          icon: '',
          title: '温馨提示',
          content: '确认放弃当前信息？',
          confirmBtn: {
            text: '确定',
            active: true,
            disabled: false,
            href: 'javascript:;'
          },
          cancelBtn: {
            text: '取消',
            active: false,
            disabled: false,
            href: 'javascript:;'
          },
          onConfirm: () => {
            _this.recordSubType = _this.form.subType
          },
          onCancel: () => {
            _this.form.subType = _this.recordSubType
            console.log('-0000000000000')
          }
        }).show()
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
